<template>
  <div class="container">
    <div class="app-container">
      <el-tree :data="treeData" :props="{label: 'name'}" default-expand-all :expand-on-click-node="false">
        <template #default="{data}">
          <el-row :style="{width: '100%'}" type="flex" justify="space-between">
            <div>{{ data.name }}</div>
            <el-row style="width: 140px;" type="flex" justify="space-between">
              <span>{{ data.managerName }}</span>
              <el-dropdown @command="onOperation($event, data.id )">
                <span class="el-dropdown-link">
                  操作<i class="el-icon-arrow-down el-icon--right" />
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="add">添加子部门</el-dropdown-item>
                  <el-dropdown-item command="edit">编辑部门</el-dropdown-item>
                  <el-dropdown-item command="del">删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-row>

          </el-row>
        </template>
      </el-tree>
    </div>

    <AddDep ref="addDep" :visible.sync="visible" :current-id="currentId" @refresh="loadData" />

  </div>
</template>
<script>
import { getDepartmentAPI, delDepartmentAPI } from '@/api/department'
import { arrayToTree } from '@/utils'
import AddDep from './AddDep.vue'
export default {
  name: 'Department',
  components: {
    AddDep
  },
  data() {
    return {
      visible: false,
      treeData: [],
      currentId: ''
    }
  },
  created() {
    this.loadData()
  },
  methods: {
    async loadData() {
      const res = await getDepartmentAPI()
      const tree = arrayToTree(res)
      this.treeData = tree
    },
    async onOperation(command, id) {
      if (command === 'add') {
        this.visible = true
        this.currentId = id
      }

      if (command === 'edit') {
        await this.$refs.addDep.getDepDetail(id)
        console.log('  ----->  ', this.$refs.addDep.getDepDetail(id))
        this.visible = true
      }

      if (command === 'del') {
        await this.$confirm('是否确认删除该部门？', '提示')
        await delDepartmentAPI(id)

        this.$message.success('删除成功')
        this.loadData()
      }
    }
  }
}
</script>

<style scoped>
.container{
  padding: 30px 140px;
  background-color: white;
  margin: 20px
}
</style>
